package com.sky.service.user.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.mapper.admin.DishFlavorMapper;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.ShoppingCart;
import com.sky.result.Result;
import com.sky.service.user.ShoppingCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void add(ShoppingCartDTO dto) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCart.setDishFlavor(dto.getDishFlavor());
        shoppingCart.setCreateTime(LocalDateTime.now());
        ShoppingCart exitShop = shoppingCartMapper.getByDishIdOrSetmealId(dto.getSetmealId(), dto.getDishId(), BaseContext.getCurrentId());
        if (exitShop != null){
            log.info("菜品或者套餐已经存在，修改套餐数量");
            shoppingCartMapper.updateNumById(exitShop.getNumber() +1,exitShop.getId());
            return;
        }
        shoppingCart.setNumber(1);


       if (dto.getDishId() != null) {
            DishVO dish = dishMapper.getDishById(dto.getDishId());
            shoppingCart.setName(dish.getName());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setDishId(dto.getDishId());
        } else if (dto.getSetmealId() != null) {
            shoppingCart.setSetmealId(dto.getSetmealId());
            SetmealVO setmeal = setmealMapper.getSetmealById(dto.getSetmealId());
            shoppingCart.setName(setmeal.getName());
            shoppingCart.setImage(setmeal.getImage());
            shoppingCart.setAmount(setmeal.getPrice());
            shoppingCart.setDishId(dto.getDishId());
        }
       shoppingCartMapper.insert(shoppingCart);

    }

    @Override
    public List<ShoppingCart> queryCart() {
        return shoppingCartMapper.queryCart(BaseContext.getCurrentId());
    }

    @Override
    public void deleteShop() {
        shoppingCartMapper.deleteShop(BaseContext.getCurrentId());
    }


}
